from enum import Enum

from .trigger import ObjectLeaveTrigger


# 联动进入报警器
class PassTrigger(ObjectLeaveTrigger):

    class Direction(Enum):
        UP = 0
        RIGHT = 1
        DOWN = 2
        LEFT = 3
    
    def __init__(self, alert_objs, pass_alert_directions):
        super().__init__(alert_objs)
        # 从↑顺时针编号
        self._pass_alert_directions_enable = [
            '↑' in pass_alert_directions,
            '→' in pass_alert_directions,
            '↓' in pass_alert_directions,
            '←' in pass_alert_directions,
         ] if pass_alert_directions else [False for _ in range(4)]

    def leave(self, obj, objs):
        # 当有物体离开时检查是否满足经过报警条件
        leave_pos = obj.get_pos()

        direction = None
        x_off, y_off = leave_pos[0] - obj.enter_pos[0], leave_pos[1] - obj.enter_pos[1]
        if abs(x_off) > abs(y_off):  # 说明是左右移动
            if x_off > 0:
                direction = self.Direction.RIGHT
            else:
                direction = self.Direction.LEFT
        else:  # 说明是上下移动
            if y_off > 0:
                direction = self.Direction.DOWN
            else:
                direction = self.Direction.UP

        if self._pass_alert_directions_enable[direction.value]:
            # 经过报警
            direction_msg = (
                '向前',
                '右侧',
                '向后',
                '左侧'
            )
            self.alert_to_cloud({
                'type': obj.label,
                'target': f'{obj.label}{direction_msg[direction.value]}经过',
                'action': direction.value + 3,  # 0~3 + 3 = 3~6
                'image': {
                    'base64': self.encode_jpg_image(obj.make_shotcut()),
                    'ext': 'jpg'
                }
            })
